import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import ElMessage from 'autoprefixer/lib/utils'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['hm-token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      // eslint-disable-next-line no-empty
      return response.data
    }
    return Promise.reject(response.data)
  }, error => {
    if (error.response) {
      if (error.response.status === 401) {
        ElMessage.error({
          message: '登录失效',
          grouping: true,
          onClose: () => {
            router.push({ name: 'login' })
          }
        })
      }
    }
    if (error.response) {
      if (error.response.status === 403) {
        ElMessage.error({
          message: '无权限',
          grouping: true,
          onClose: () => {
            router.push({ name: '403' })
          }
        })
      }
    }
    return Promise.reject(error)
  }
)

export default service
